package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class RegDemo {
    public static void main(String[] args) throws Exception {
        UserInfo userInfo = InputUtil.getInputObject(new UserInfo(),"欢迎注册","注册");
        System.out.println(userInfo);

        /*Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        System.out.println("请输入昵称");
        String nickname = sc.nextLine();
        System.out.println("请输入年龄");
        int age = sc.nextInt();*/

     int num= reg(userInfo);

        if(num>0){
            System.out.println("注册成功");
        }

    }
    public static int reg(UserInfo userInfo)throws Exception{
        //1:加载驱动
        //不同数据库厂商实现的Driver接口的实现类包名和实现类名不完全一样
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2:使用DriverManager利用驱动与数据库建立链接，得到Connection对象
        Connection connection = DriverManager.getConnection(
                //数据库地址格式:jdbc:mysql://数据库IP:端口/数据库名?一堆参数
                "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",//数据库用户名
                "root"//数据库密码
        );

        System.out.println("成功链接数据库!");

        //3:通过连接对象创建用于执行SQL语句的语句对象:Statement
        Statement statement = connection.createStatement();

        String sql = "INSERT INTO userinfo(username,password,nickname,age) "+
                "VALUES('"+userInfo.getUsername()+"','"+userInfo.getPassword()+"','"+userInfo.getNickname()+"',"+userInfo.getAge()+")";

        int num = statement.executeUpdate(sql);


        connection.close();
        return num;

    }
}
